import json
from todo import Todo
import os


class TodoManager:
    todos = []

    def create(self, title):
        todo = Todo(title)
        TodoManager.todos.append(todo)
        self.save()
        return todo

    def list_todos(self):
        return TodoManager.todos

    def get_todo_byid(self, id):
        for i in self.list_todos():
            if i.id == id:
                return i

    def mark_completed(self, id):
        todo = self.get_todo_byid(id)
        if todo is not None:
            todo.completed = True
            self.save()
        return todo

    def save(self, filename='todo.json'):
        data = dict(num=Todo.id_s, todo=[x.__dict__ for x in TodoManager.todos])
        todo = json.dumps(data, ensure_ascii=False, indent=2)
        with open(filename, 'w', encoding='utf-8') as f:
            f.write(todo)

    def load(self, fliename='todo.json'):
        with open(fliename, 'r', encoding='utf-8') as f:
            data = f.read()
            text = json.loads(data)
        if 'num' in text and 'todo' in text:
            Todo.id_s = text['num']
            TodoManager.todos = [Todo(**x) for x in text['todo']]
